/****************************************************
 * 
 * home soft 版权所有.
 * 
 *****************************************************/

package com.homesoft.runtime.core;

import java.util.ArrayList;
import java.util.List;

import com.homesoft.runtime.config.ConfigurationManager;
import com.homesoft.runtime.log.ILog;
import com.homesoft.runtime.log.LogLevel;
import com.homesoft.runtime.log.LogManager;

/**
 * @author lihg
 * @data 2012-9-12
 */
public class RuntimeListenerManager {
	private RuntimeEventArgs _runtimeEventArgs = null;
	private List<IRuntimeListener> _listeners;
	private static ILog logger = LogManager
			.getLogger(RuntimeListenerManager.class);

	protected RuntimeListenerManager() {
		this._listeners = new ArrayList<IRuntimeListener>();
	}

	public void startListener() {
		long beginLogId = logger.beginWriteTraceLog(LogLevel.Info, "开始启动所有监听器");
		this._runtimeEventArgs = PrepareRuntimeEventArg();

		for (IRuntimeListener listener : this._listeners) {
			long beginLogId1 = logger.beginWriteTraceLog(LogLevel.Info,
					"开始启动监听器: " + listener.getClass().getName());
			listener.onStart(_runtimeEventArgs);
			logger.endWriteTraceLog(beginLogId1, LogLevel.Info, "启动监听器完成: "
					+ listener.getClass().getName());
		}
		logger.endWriteTraceLog(beginLogId, LogLevel.Info, "启动所有监听器完成");
	}

	/**
	 * @return
	 */
	private RuntimeEventArgs PrepareRuntimeEventArg() {
		return new RuntimeEventArgs(ConfigurationManager.getConfiguration());
	}

	public void stopListener() {
		long beginLogId = logger.beginWriteTraceLog(LogLevel.Info, "开始停止所有监听器");
		for (IRuntimeListener listener : this._listeners) {
			listener.onStop(_runtimeEventArgs);
		}
		logger.endWriteTraceLog(beginLogId, LogLevel.Info, "停止所有监听器完成");
	}

	public void clearListeners() {

		stopListener();
		_listeners.clear();
	}

	public boolean registerListener(IRuntimeListener listener) {
		if (!(exists(listener))) {
			this._listeners.add(listener);
			return true;
		}
		return false;
	}

	private boolean exists(IRuntimeListener listener) {
		for (IRuntimeListener l : this._listeners) {
			if (l.getClass() == listener.getClass()) {
				logger.writeTraceLog(LogLevel.Info, String.format(
						"已存在类型相同的监听器[{0}]", listener.getClass().getName()));
				return true;
			}
		}
		return false;
	}
}
